const { MongoClient, ObjectId } = require('mongodb');

//连接MongoDB
function connect() {
    return new Promise((resolve, reject) => {
        MongoClient.connect('mongodb://localhost:27017', function (err, client) {
            if (err) throw err;
            //连接数据库，无则自动创建
            let db = client.db('Myblog');

            resolve({ db, client })

        });
    })
}
/**
 * 
 * @param {String} colName          集合名称
 * @param {Object|Array} data       添加的数据
 * @returns 
 */
async function insert(colName, data) {
    const { db, client } = await connect();
    const col = db.collection(colName)
    let result
    try {
        if (Array.isArray(data)) {
            await col.insertMany(data)
        } else {
            await col.insertOne(data)
        }
        result = true
    } catch (err) {
        result = false
    }
    client.close();
    return result;
}

/**
 * 
 * @param {string} colName   集合名称 
 * @param {string} query     筛选条件(_id)
 * @returns 
 */
async function remove(colName, query = {}) {
    const { db, client } = await connect();
    const col = db.collection(colName);
    //处理ObjectID
    if (query._id) {
        query._id = ObjectId(query._id)
    }
    let result, num = 0
    if (query === {}) {
        result = false;
        client.close()
        return {
            result
        }
    }
    try {
        let aw = await col.deleteOne(query)
        num = aw.deletedCount
        result = true
    } catch (err) {
        result = false
    }
    client.close()
    return { result, num };
}


/**
 * 
 * @param {String} colName  集合名称
 * @param {Object} query    查询条件
 * @param {Object} newData  修改的数据（用户需自带操作符，如：{$set:{}}）
 */
async function updata(colName, query, newData) {
    if (query === undefined) {
        throw new Error('更新操作必须包含匹配条件');
    }
    const { db, client } = await connect();
    const col = db.collection(colName);

    // 处理ObjectId
    if (query._id) {
        query._id = ObjectId(query._id)
    }
    console.log(newData);
    let result
    try {
        await col.updateMany(query, newData)
        result = true;
    } catch (err) {
        result = false
    }

    client.close();
    return result;
}

async function find(colName, query = '', { limit, skip } = {}) {
    const { db, client } = await connect()
    //获取集合
    const col = db.collection(colName);
    if (query._id) {
        query._id = ObjectId(query._id)
    }
    // console.log(query);
    //查找
    // if (!query) query = '';
    let result = col.find(query);

    //控制数量
    if (limit) {
        result = result.limit(limit)
    }
    if (skip) {
        result = result.skip(skip)
    }

    const data = await result.toArray();

    // console.log(Object.prototype.toString.call(arr));
    //关闭数据库连接
    // console.log(data);
    client.close()
    return data
}

module.exports = {
    insert,
    remove,
    updata,
    find
}